import { SERVER_URL } from './config';
const websocket = new WebSocket(SERVER_URL);

/**
 * @description 当前 WebSocket 的链接状态
 * 0 [CONNECTING] 正在链接中
 * 1 [OPEN] 已经链接并且可以通讯
 * 2 [CLOSING] 连接正在关闭
 * 3 [CLOSED] 连接已关闭或者没有链接成功
 */
const readState = websocket.readyState;

// 发送消息
const send = (text) => {
	if (typeof text !== 'string') {
		text = text.toString();
	}
	websocket.send(text);
};

/**
 * 连接状态变为 CLOSED 时被调用
 */
websocket.onclose = (event) => {
	console.log('🌈 —— close --->', event);
};

/**
 * websocket的连接由于一些错误事件的发生时被调用
 */
websocket.onerror = (event) => {
	console.log('🌈 —— error --->', event);
};

/**
 * WebSocket 接收到新消息时被触发
 */
websocket.onmessage = (event) => {
	console.log('🌈 —— message --->', event);
};

/**
 * 当WebSocket 的连接状态readyState 变为1时调用
 */
websocket.onopen = (event) => {
	console.log('🌈 —— open --->', event);
};
